﻿/// <reference path="../../../../Sustainalytics.Core.UI/modules/Routing/services/RoutingService.ts" />
module Sustainalytics.Controversies {
    import Company = Sustainalytics.Company;
    import Charts=Sustainalytics.Charts;
    

    export class MapBaseController {
        public mapChartOptions: Charts.MapChartOptions;
        private mapImageLocations:Charts.MapImageLocation[];
        protected controversiesController: ControversiesController;
        protected controversyIndicatorController: ControversyIndicatorsController;
        public mapIsLoading: boolean = true;
        public addressDetails:string;
        public isInitLoading: boolean;
        public showLegend: boolean;
        public isSummary:boolean;
        private userId: string;
        private location: any;
        public notFoundMessage: string = '';
        public noClaims: boolean = false;
        public companyId: string;
        

        constructor(
            protected $rootScope: ng.IScope,
            protected $scope: Company.ICompanyBasedScope,
            protected $q: ng.IQService,
            protected $timeout: ng.ITimeoutService,
            protected RoutingService: Routing.IRoutingService,
            protected controversiesService: IControversiesService,
            protected $location:ng.ILocationService
        
            ) {
            var ctx = this;
            ctx.location = RoutingService.getRouteEngineAdapter().getCurrentPath();
            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.isSummary = true;
            ctx.showLegend = true;
            ctx.mapImageLocations = [];
            ctx.userId = this.$rootScope['userInfo'].userId;
            ctx.controversiesController = $scope['controversies'];
            ctx.controversyIndicatorController = $scope['controveryIndicators'];
            ctx.companyId = this.controversiesController.company.id;
           // this.init();
            ctx.hackCloseDescriptionWindowAmChart();
        }


        private hackCloseDescriptionWindowAmChart(): void {

            var ctx = this;

            $('body').click(event => {

                $('.ammapDescriptionWindow.amcharts-description-div').remove();

            });

            $('#worldMapIncidentSummary').click(event => { //TODO it may be a need to foind another solution for this
                if ($(event.target).attr('id')) {
                    $('.ammapDescriptionWindow.amcharts-description-div').remove();
                    ctx.goToIncidentDetail($(event.target).attr('id'));
                    return;
                }  
                if (!$(event.target).closest('.ammapDescriptionWindow.amcharts-description-div').length) {
                    $('.ammapDescriptionWindow.amcharts-description-div').remove();
                }
            });
            //$(document).load(() => {
            //   if (!ctx.showLegend) {
            //       $('.amChartsLegend.amcharts-legend-div').remove();
            //   }
            //});

        }
        

        public setDataMap(): ng.IPromise<MapDataDto[]> {
            return null;
        }

        private init(): void {

            //var dataMap = this.controversiesService.getIncidentsMapLocationForCompany(this.controversiesController.company.id);
            //var dataMap = this.setDataMap();
            //this.redrawMap(dataMap);
        }

        protected  redrawMap(dataMap: ng.IPromise<MapDataDto[]>): void {
            var ctx = this;
            if (!dataMap) return;
            dataMap.then(succes => {
                ctx.mapImageLocations = [];
                if (!succes) return;
                if (succes.length == 0) {
                    ctx.mapChartOptions = ctx.getMapIncidenDataCompany();
                    return;
                }
                var desc = "";
                var tooltip = "";
                for (var i = 0; i < succes.length; i++) {
                    var current = succes[i];

                    var color = current.mapLocationType == MapLocationType.HQ ? "#41b1a5" : "#FCB01A";
                    if (!ctx.isSummary) color = "#E1E1E1";
                    var link = "#"+ctx.$location.path();
                    var size = current.mapLocationType == MapLocationType.HQ ? 1.5 : 1.5;
                    var addres = current.geoData.address ? current.geoData.address : "";
                    desc = "";
                    for (var j = 0; j < current.detailsToolTip.length; j++) {
                        var value2 = current.detailsToolTip[j];
                        if(!value2) continue;
                        desc += '<p><a id=' + value2.link + ' href=' + link+'>' + value2.name + '</a></p>';
                        
                    }
                    if (tooltip.trim() != '') tooltip += ',';
                    tooltip += addres;
                    var split = tooltip.split(',');
                    var outputArr = [];
                    $.each(split, function (i, e) {
                        if ($.inArray(e, outputArr) == -1) outputArr.push(e);
                    });
                    tooltip = outputArr.join(',');
                    //console.log(desc);
                    ctx.mapImageLocations.push(new Charts.MapImageLocation(addres, color, "circle", "", current.geoData.latitude, current.geoData.longitude, size, addres, desc));
                }
                ctx.addressDetails = tooltip;
                $('#addressDetails').text(tooltip);
                ctx.mapChartOptions = ctx.getMapIncidenDataCompany();
            }, error => {
                    ga('create', 'UA-4379897-6', {
                        'userId': this.$rootScope['userInfo'].userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: HistoricalPerformance Controller -> Error loading Historical Performance Summary' });
                });
        }

        private goToIncidentDetail(incident: String): void {
            //alert(incident);
            var ctx = this;
            console.log(incident);
            var split = incident.split(';');
            if (split.length != 6)
                return;
            var cidDto = new ControversyIndicatorDto();
            cidDto.id = split[1];
            var evIdDto = new EventIndicatorDto();
            evIdDto.id = split[2];
            var iiDto = new IncidentDto();
            iiDto.id = split[5];
            evIdDto.baseEventIndicatorId = split[3];
            ctx.controversiesController.selectedControversyIndicator = cidDto;
            ctx.controversiesController.selectedEventIndicator = evIdDto;
            if (!ctx.controversyIndicatorController) {
                ctx.$rootScope['incident_map_selected_summary'] = iiDto;
                ctx.$rootScope['incident_map_current_url'] = ctx.$location.path();
               
                switch (split[0]) {
                case "Environment": //TODO should be a refactor
                    ctx.controversiesController.changeView(ControversiesViewNames.Environment);
                    break;
                case "Social":
                    ctx.controversiesController.changeView(ControversiesViewNames.Social);
                    break;
                case "Governance":
                    ctx.controversiesController.changeView(ControversiesViewNames.Governance);
                    break;
                default:
                    ctx.controversiesController.changeView(ControversiesViewNames.Summary);
                }
            }
            if (ctx.controversyIndicatorController) {
                ctx.controversyIndicatorController.selectIncident(iiDto);
            } //alert(incident + " " + this.number);
            //this.number++;
        }

        public getMapIncidenDataCompany(): Charts.MapChartOptions {
            var ctx = this;
            var valoare = ctx.createMap();
            valoare.dataProvider = new Charts.MapDataProvider("worldLow", this.mapImageLocations);
            
            var legend2 : Charts.MapLegendData[]=[];
            if (ctx.showLegend) {
                legend2.push(new Charts.MapLegendData("Incident", "#FCB01A"));
                legend2.push(new Charts.MapLegendData("Headquarters", "#41b1a5"));
            }

            valoare.legend = new Charts.MapLegend(240, 27, 27, true,
                1, 0, "#FFFFFF", "#ffffff", 1, 0, 10, true, (ctx.showLegend)?legend2:null,"bottom"
            );
            return valoare;
        }


        private createMap(): Charts.MapChartOptions {
            var options: any = {
                "type": "map",
                "theme": "light",
                "pathToImages": "http://www.amcharts.com/lib/3/images/",
                "areasSettings": {
                    "autoZoom": true,
                    "selectedColor": "#CC0000"
                },
                //"backgroundAlpha": 0,

                //"imagesSettings": {
                //    "color": "#CC0000",
                //    "rollOverColor": "#CC0000",
                //    "selectedColor": "#000000"
                //}              
            };
            return options;
        }
    }

    export class MapIncidentController extends MapBaseController {

        constructor(protected $rootScope: ng.IScope,
            protected $scope: Company.ICompanyBasedScope,
            protected $q: ng.IQService,
            protected $timeout: ng.ITimeoutService,
            protected RoutingService: Routing.IRoutingService,
            protected controversiesService: IControversiesService,
            protected $location: ng.ILocationService) {

            super($rootScope, $scope, $q, $timeout, RoutingService, controversiesService, $location);
            
            
            var ctx = this;
            ctx.setDataMap();
        }

        public setDataMap(): ng.IPromise<MapDataDto[]> {
            var ctx = this;
            var dataMap = ctx.controversiesService.getIncidentsMapLocationForCompany(this.controversiesController.company.id);
            ctx.redrawMap(dataMap);
            return dataMap;
        }
    }

    export class MapEventIndicatorIncidentController extends MapBaseController {

        

        constructor(protected $rootScope: ng.IScope,
            protected $scope: Company.ICompanyBasedScope,
            protected $q: ng.IQService,
            protected $timeout: ng.ITimeoutService,
            protected RoutingService: Routing.IRoutingService,
            protected controversiesService: IControversiesService,
            protected $location: ng.ILocationService) {

            super($rootScope, $scope, $q, $timeout, RoutingService, controversiesService, $location);
            var ctx = this;
            ctx.showLegend = false;
            ctx.isSummary = false;
            
            
            $scope.$watch(() => {
                return ctx.controversyIndicatorController.selectedEventIndicator;
            },() => {
                $('#worldMapIncidentSummary').empty();
                ctx.setDataMap();
            });
            ctx.setDataMap();
        }

        public setDataMap(): ng.IPromise<MapDataDto[]> {
            var ctx = this;
            if (!ctx.controversyIndicatorController) return ctx.$q.when(null);
            if (!ctx.controversyIndicatorController.selectedEventIndicator) return ctx.$q.when(null);
            if (!ctx.controversyIndicatorController.selectedEventIndicator.baseEventIndicatorId && !ctx.controversyIndicatorController.selectedEventIndicator.id) return ctx.$q.when(null);
            
            var selectEvId = ctx.controversyIndicatorController.selectedEventIndicator.baseEventIndicatorId;
            if (!selectEvId) selectEvId = ctx.controversyIndicatorController.selectedEventIndicator.id;
            //var selectEvId = ctx.controversyIndicatorController ? !(ctx.controversyIndicatorController.selectedEventIndicator.baseEventIndicatorId ? ctx.controversyIndicatorController.selectedEventIndicator.id : ""):"";
            
            var dataMap = ctx.controversiesService.getIncidentsMapLocationByEventIndicator(ctx.controversiesController.company.id, selectEvId);
            this.redrawMap(dataMap);
            return dataMap;
        }
    }





    export var controllerName = "MapBaseController";
    angular.module(controversiesModuleName).controller(controllerName,
        ['$rootScope', '$scope', '$q', '$timeout', 'RoutingService', 'ControversiesService', '$location', MapBaseController]);

   export  var controllerNameIncident = "MapIncidentController";
    angular.module(controversiesModuleName).controller(controllerNameIncident,
        ['$rootScope', '$scope', '$q', '$timeout', 'RoutingService', 'ControversiesService', '$location', MapIncidentController]);

    export var controllerNameIncidentEventIndicator = "MapEventIndicatorIncidentController";
    angular.module(controversiesModuleName).controller(controllerNameIncidentEventIndicator,
        ['$rootScope', '$scope', '$q', '$timeout', 'RoutingService', 'ControversiesService', '$location', MapEventIndicatorIncidentController]);
}